--- title: "Homework 2 R Exercise" output: pdf_document: default html_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` This is an exercise to demonstrate simple R mathematical functions to assist with computing expected values and variances for discrete random variables. We will use the data in 4.30 in the text measuring environmental vulnerability of amphibians. This is a good example to use since the EVS (the environmental vulnerability score) has 18 levels (from 3 to 20) and hand calculations would be tedious. Start out by saving a vector of the outcomes, the EVS score---which serves as ***x***---and a vector of probabilities, ***p(x)=P(X=x)***. Note that the probabilities are derived from the observed outcomes as with many exercises in the text, which isn't always a wise choice for a model. We use ***cbind*** to combine vectors as columns; the output makes it is easier to visualize the probabilities assigned to each outcome. The ***round*** command reduces the number of digits displayed for Prob_EVS. I also had to restore the name of Prob_EVS after I operated on it with the ***round*** command; otherwise the output would have had no label for the second column. ```{r eval=FALSE} EVS=3:20 Prob_EVS=c(1,1,7,10,9,19,17,30,25,31,46,52,50,44,24,9,7,0)/382 cbind(EVS,Prob_EVS=round(Prob_EVS,4)) ``` In class, I shared code to display a graph of a probability distribution (the hypergeometric distribution); let's graph the probability distribution for this example. Comment. ```{r eval=FALSE} plot(EVS,Prob_EVS,type="h",lend=1,lwd=4,ylab="p(EVS)") ``` The expected value, $\mu$, and variance, $\sigma^2$, are readily computed with vectors. We use * to multiply the vectors element-by-element; other operators would be used for vector multiplication. ````{r eval=FALSE} Expected_EVS=sum(EVS*Prob_EVS) Variance_EVS=sum(Prob_EVS*(EVS-Expected_EVS)^2) SD_EVS=sqrt(Variance_EVS) ``` Do the output values for the mean $\mu$ and standard deviation $\sigma$ appear to make sense? There are other R functions that could simplify the steps even more (e.g., ***weighted.mean***), but we chose to use procedures that mimic the calculations in the text.